import React, {Component} from 'react';
import {StyleSheet, Text, View, Image, 
  Dimensions,ScrollView,Modal,WebView,StatusBar,
  TouchableOpacity,
} from 'react-native';
import Orientation from 'react-native-orientation';
import RefreshListView, {RefreshState} from 'react-native-refresh-list-view';
import { TipModal } from '../../component/Tips';
import Loading from '../../component/Loading';
import BackButton from '../../component/BackButton';
import {jumpPage} from '../../common/common'
import {BASEURL} from '../../api/api'
import MyButton from '../../component/MyButton';
import NoData from '../../component/NoData';
import Search from './Search';
import VideoPlayer from 'react-native-video-player';
let {height, width} = Dimensions.get('window');
var noMore = false;
var pageNo = 0;
var pageSize = 9;
export default class Templ extends Component{
  static navigationOptions = ({ navigation }) =>{
    return{
      header:null,
      // title: '选择镜头',
      // headerStyle:{
      //   marginTop:0,
      //   height:40,
      // },
      // headerRight:(<View></View>),
      // headerLeft:<BackButton navigation = {navigation}/>
    }
  };
  constructor(props){
    super(props);
    this.state = ({
      keyword:'',
      showList:false,
      modal: false,
      type:1,
      loading:false,
      leftActive:0,
      activeLensTypeId:'',
      activeLensSecondTypeId:'',
      topActive:0,
      selectLens:{},
      leftData:[
      ],
      data:[
      ],
			lensSecondTypeList:[],
			video: { width: undefined, height: undefined, duration: undefined },
    })
  }
  componentWillMount(){
    Orientation.lockToLandscape();
    this._getTypeList();
    // setTimeout(()=>{
    //   this._getTempList(0);
    // },100)
  }
  componentDidMount(){
    pageNo = 0;
    noMore = false;
  }
  onHeaderRefresh = () => {
    //alert('header')
  }
  onFooterRefresh = () => {
    //alert('header')
    console.log('noMore',noMore);
    console.log('--end')
    if(noMore){
  		return;
    }
    pageNo++;

    console.log('pageNo=',pageNo);
    //if(pageNo == 0 || pageNo == 1) return;
    
    if(this.state.topActive == 0){ //全部
      this._getLensList();
    } else {
      this._getLensListTwo();
		}
  	//this.fetchData(pageNo);
    this.setState({refreshState: RefreshState.FooterRefreshing});
  }
  _getTypeList(){
    fetch(BASEURL+'temp/lensTypeList')
    .then(res=>res.json())
    .then(response=>{
      //console.log(response);
      this.setState({
        leftData:response.list,
        activeLensTypeId:response.list[0].lensTypeId,
      },()=>{
        this._getSecondTypeList(response.list[0].lensTypeId);
        //this._getLensList(response.list[0].lensTypeId);
      })
    })
  }
  //获取镜头二级类型列表
  _getSecondTypeList(lensTypeId){
    fetch(BASEURL+'lens/getLensTypeSecondList?lensTypeId='+lensTypeId)
    .then(res=>res.json())
    .then(response=>{
      //console.log(response);
      if(response.succ == '1'){
        //alert('show)');
        this.setState({
          lensSecondTypeList:response.list,
          //showList: true,
        },()=>{
          this.onFooterRefresh();
					//pageNo = 1;
					//this._getLensList(lensTypeId);
        })
      }
    })
  }
  //根据一级类型获取镜头列表
  _getLensList(){
    //this.refs.tipModal._loading();
    fetch(BASEURL+'temp/lensListByTypeId?lensTypeId='+this.state.activeLensTypeId+'&pageSize='+pageSize+'&pageNo='+pageNo)
    .then(res=>res.json())
    .then(response=>{
      console.log('list',response);

      this.refs.tipModal._close();
      if(response.succ == '1'){
        let data = this.state.data;
        if(pageNo == 1){
          data = [];
        }
        console.log('length=',response.list.result.length)
        if(!response.list.result || response.list.result.length<pageSize ){
          noMore = true
          this.setState({
            data:data.concat(response.list.result),
            loading:false,
            refreshState: RefreshState.NoMoreData,
          })
        } else {
          this.setState({
            data:data.concat(response.list.result),
            loading:false,
            refreshState: RefreshState.Idle,
          })
        }
      }
      
      // this.setState({
      //   loading:false,
      //   data:response.list,
      // })
    })
  }
  //根据二级类型获取镜头列表
  _getLensListTwo(){
    //this.refs.tipModal._loading();
    fetch(BASEURL+'temp/lensListBySecondTypeId?lensTypeId='+this.state.activeLensSecondTypeId+'&pageNo='+pageNo+'&pageSize='+pageSize+'&keyword='+this.state.keyword)
    .then(res=>res.json())
    .then(response=>{
      console.log('list',response);
      this.refs.tipModal._close();
      if(response.succ == '1'){
        let data = this.state.data;
        if(pageNo == 1){
          data = [];
        }
        if(!response.list.result || response.list.result.length<pageSize ){
          noMore = true
          this.setState({
            data: data.concat(response.list.result),
            loading:false,
            refreshState: RefreshState.NoMoreData,
          })
        } else {
          this.setState({
            data: data.concat(response.list.result),
            loading:false,
            refreshState: RefreshState.Idle,
          })
        }
      }
      // this.setState({
      //   loading:false,
      //   data:response.list,
      // })
    })
  }
  _select(lens){
		// this.refs.tipModal._loading();
    // this.setState({
    //   selectLens: lens,
    //   modal: true,
    //   url: BASEURL+'temp/lensHtml?height='+width+'&width='+height+'&isLens=1&lensId='+lens.lensId
		// })
		//'http://59.110.158.134/1558923145080/test-name.mp4'
		this.setState({
			selectLens:lens,
			modal: true,
			videoUrl: lens.mp4,//BASEURL+'lens/playVideo?lensId='+lens.lensId+'&fileName='+lens.mp4,
			thumbnail: BASEURL+'getImage?imageName='+ lens.lensId+'/'+lens.lensImg
		})
  }
  _selectLens(){
    const {state} = this.props.navigation;
    state.params.callback(this.state.selectLens);
    this.props.navigation.goBack(); 
  }
  //左侧菜单点击
  _leftSelect(index,lensTypeId){
    noMore = false;
    pageNo = 0;
    this.setState({
      data:[],
      topActive: 0,
      leftActive: index,
      activeLensTypeId: lensTypeId,
      activeLensSecondTypeId: '',
    },()=>{
      this._getSecondTypeList(lensTypeId);
    })
    
    // 、this._getLensList(lensTypeId);
  }
  //二级菜单类型点击
  secondTypeSelect(index,lensSecondType){
    this.setState({
      keyword:'',
      topActive:index,
      activeLensSecondTypeId:lensSecondType
    },()=>{
      noMore = false;
      pageNo = 1;
      if(index == 0){
        this._getLensList();
      } else {
        this._getLensListTwo();
      }
    })
    
  }
  renderSecondType(){
    let {lensSecondTypeList} = this.state;
    let array = [];
    let style={
      alignItems:'center',
      paddingLeft:8,
      paddingRight:8,
    }
    array.push(
      <TouchableOpacity style={style} onPress={()=>this.secondTypeSelect(0)} key="0">
        <Text style={[{fontSize:this.state.topActive==0?17:15,padding:8,color:this.state.topActive==0?'#2596ff':'black'}]}>全部</Text>
        <View style={{height:2,width:20,backgroundColor:this.state.topActive==0?'#2596ff':'white'}}></View>
      </TouchableOpacity>
    )
    for(let i=0; i<lensSecondTypeList.length; i++){
      let item = lensSecondTypeList[i];
      array.push(
        <TouchableOpacity style={style} onPress={()=>this.secondTypeSelect(i+1,item.pkId)} key={item.pkId}>
          <Text style={[{fontSize:this.state.topActive==(i+1)?17:15,padding:8,color:this.state.topActive==(i+1)?'#2596ff':'black'}]}>{item.typeName}</Text>
          <View style={{height:2,width:20,backgroundColor:this.state.topActive==(i+1)?'#2596ff':'white'}}></View>
        </TouchableOpacity>
      )
    }
    return array;
  }
  _renderLeft(){
    let {leftData} = this.state;
    if(leftData.length == 0) return;
    var leftCell = [];
    for(let i=0; i<leftData.length; i++){
      let item = leftData[i];
      leftCell.push(
        <TouchableOpacity key={i} onPress={()=>{this._leftSelect(i,item.lensTypeId)}} activeOpacity={0.6}
          style={[styles.leftCell,i==this.state.leftActive?styles.leftCellActive:null]}>
          <Text style={{fontSize:16}}>{item.typeName}</Text>
        </TouchableOpacity>
      )
    }
    return leftCell;
  }
  _renderContent(){
    let {data} = this.state;
    var rightCell = [];
    for(let i=0; i<data.length; i++){
      let item = data[i];
      rightCell.push(
        <Cell  key={i}   style={{marginBottom:i==data.length-1?0:0}}
        press={()=>this._select(item)} data={item} />
      )
    }
    return rightCell;
	}
	_onLoadEnd(){
		this.refs.tipModal._close();
	}
  _toggle(){
    this.setState({
      showBtn: !this.state.showBtn
    })
  }
  _renderItem = ({item,index}) =>{
    //alert(1)
    let data = this.state.data;
    return(
      <Cell  key={index}  style={{borderColor:'red',borderWidth:0}}
        press={()=>this._select(item)} data={item} />
    )
  }
  _keyExtractor = (item, index) => index.toString();
  _separator = () => {
    return <View style={{height:0,backgroundColor:'#f0f0f0'}}/>;
  }
  _onChange(val){
    this.setState({
      keyword: val,
    })
  }
  _search(){
    noMore = false;
    pageNo = 1;
    this._getLensListTwo();
  }
  render(){
    //console.log('len',this.state.data.length)
    console.log('showList',this.state.showList)
    return(
      <View style={styles.container}>
        <StatusBar hidden={true} backgroundColor='black' />
        <View style={{height:50,flexDirection:'row',alignItems:'center',justifyContent:'space-between'}}>
          <View style={{flexDirection:'row',justifyContent:'center'}}>
            <BackButton navigation = {this.props.navigation}/>
            <View><Text style={{fontSize:18,color:'#333'}}>镜头库</Text></View>
          </View>
          
          <View style={{width:height/5*2}}>
            <Search placeholder='搜索镜头...'
						search={()=>this._search()} 
						subStyle={{backgroundColor:'#f0f0f0',marginTop:5,paddingRight:5}}
            onChange={(val)=>this._onChange(val)}
            />
          </View>
        </View>
        <View style={styles.content}>
          <View style={styles.leftView}>
            {this.state.leftData.length == 0 ? <NoData /> : <ScrollView showsVerticalScrollIndicator={false}>{this._renderLeft()}</ScrollView>}
          </View>
          { this.state.loading ? <Loading/> : 
          (
            <View style={{borderWidth:0,borderColor:'black',flex:1}}> 
              <View>
                <ScrollView horizontal={true} showsHorizontalScrollIndicator={false} style={{borderColor:'red',borderWidth:0,paddingTop:4,paddingBottom:4}}>
                  {this.renderSecondType()}
                </ScrollView>
              </View>
         
              <View style={styles.rightView}>
              { //this.state.showList?
                <RefreshListView
                  //horizontal={true}
                  style={{flexDirection:'row',flexWrap:'wrap',flex:1,}}
                  data={this.state.data}
                  keyExtractor={this._keyExtractor}
                  renderItem={this._renderItem}
                  refreshState={this.state.refreshState}
                  onHeaderRefresh={this.onHeaderRefresh}
                  onFooterRefresh={this.onFooterRefresh}
                  ItemSeparatorComponent={this._separator}
                  numColumns={3}
                  // 可选
                  footerRefreshingText= '数据加载中...'
                  footerFailureText = '--数据加载失败--'
                  footerNoMoreDataText= '--没有更多了--'
                />
              }
              </View>
            </View>
            
          )
          
          }
        </View>
        <TipModal ref="tipModal"/>
        <Modal animationType='none' 
          transparent={true} 
          visible={this.state.modal} 
          onRequestClose={() => {this.setState({modal:false})}}
          style={[styles.modal]}
          >
          <View style={{flex:1,backgroundColor:'rgba(0,0,0,1)'}}>
            {/* <WebView style={{flex:1,margin:0}}
              ref="webView"
              source={{uri:this.state.url}}
              javaScriptEnabled={true}
              scrollEnabled={false}
              domStorageEnabled={true}
              decelerationRate="normal"
              startInLoadingState={true}
              scalesPageToFit={true}
              allowUniversalAccessFromFileURLs={true }
							allowsInlineMediaPlayback={true}
							onLoadEnd={()=> this._onLoadEnd()}
						/> */}
						<View style={{flex:1,backgroundColor:'black',justifyContent:'space-between'}}>
							<TouchableOpacity style={{position:'absolute',left:20,top:20}} onPress={()=>this._close()}>
								<Image source={require('../../images/temp/icon_close.png')} style={{width:24,height:24}}/>
							</TouchableOpacity>
							<View></View>
							<VideoPlayer 
								endWithThumbnail
								thumbnail={{ uri: this.state.thumbnailUrl }}
								video={{ uri: this.state.videoUrl }}
								videoWidth={this.state.video.width}
								videoHeight={this.state.video.height}
								resizeMode="contain"
								autoplay={true}
								duration={this.state.video.duration/* I'm using a hls stream here, react-native-video
									can't figure out the length, so I pass it here from the vimeo config */}
								ref={r => this.player = r}
								//customStyles={customStyles}
							/>
							<View></View>
						</View>
          </View>
          
          <View style={{flex:1,position:'absolute',left:0,top:0,right:0,bottom:0,}}>
             <TouchableOpacity style={styles.mView} activeOpacity={1.0} onPress={() => this._toggle()}>
              <View style={[styles.lView]}>
                <MyButton text='选择' press={()=>this._selectLens()} 
                  btnStyle={{marginLeft:0,marginRight:1,marginTop:0,
                  paddingLeft:20,paddingRight:20,backgroundColor:'rgba(0,0,0,0.4)',
                marginBottom:1,borderRadius:5,}}/>
                <MyButton text='返回' press={()=>{this.setState({modal:false})}} 
                  btnStyle={{marginLeft:1,marginRight:1,marginTop:30,
                  paddingLeft:20,paddingRight:20,backgroundColor:'rgba(0,0,0,0.4)',
                marginBottom:1,borderRadius:5,}}/>
              </View>
            </TouchableOpacity>
          </View>
         
        </Modal>
      </View>
    )
  }
}
class Cell extends Component{
  render(){
    let {lensId, lensImg} = this.props.data;
    let imgUrl = BASEURL+'getImage?imageName='+ lensId+'/'+lensImg;
    //console.log('imgUrl',imgUrl);
    return(
      <TouchableOpacity style={[styles.cellViewStyle,this.props.style,]} activeOpacity={0.6} onPress={this.props.press}>
        <Image style={styles.cellImg} source={{uri:imgUrl}}/>
        <Text style={styles.cellText}>{this.props.data.lensName}</Text>
      </TouchableOpacity>
    )
  }
}
const styles = StyleSheet.create({
  activeText:{
    borderBottomColor:'#2596ff',
    borderBottomWidth:2,
  },  
  lView:{
    backgroundColor:'rgba(0,0,0,0.0)',
    opacity:1,
    justifyContent:'center',
    alignItems:'center',
    marginRight:10,
  },
  mView:{
    flex:1,
    borderWidth:0,
    flexDirection:'row',
    //opacity:0.5,
    justifyContent:'flex-end',
    alignItems:'center',
    backgroundColor:'rgba(0, 0, 0, 0.0)',
  },
  modal:{
    flex:1,
  },
  cellViewStyle:{
    marginTop:10,
    marginLeft:5,
    width:(height/8*7-30)/3,
    backgroundColor:'#fff',
    // borderWidth:StyleSheet.hairlineWidth,
    // borderColor:'black',
    paddingBottom:8,
  },
  cellText:{
    padding:5,
  },
  cellImg:{
    width:(height/8*7-30)/3,
    height:(height/8*7-30)/3/16*9,
  },
  leftCell:{
    padding:15,
    paddingLeft:10,
    paddingRight:10,
    justifyContent:'center',
    alignItems:'center',
    backgroundColor:'#f0f0f0',
    borderLeftColor:'#f0f0f0',
    borderLeftWidth:4,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor:'#ccc',
  },
  leftCellActive:{
    backgroundColor:'#fff',
    borderLeftColor:'#2596ff',
  },
  leftView:{
    // borderWidth:1,
    // borderColor:'gray',
		//width:height/7,
		width:120,
  },
  rightView:{
    paddingLeft:5,
    // borderWidth:1,
    // borderColor:'green',
    flex:1,
    height:'100%',
    flexDirection:'row',
    flexWrap:'wrap',
  },
  content:{
    flexDirection:'row',
    flex:1,
    // borderWidth:1,
    // borderColor:'red',
  },
  headerText:{
    fontSize:18,
    color:'#000',
    padding:10,
  },
  container: {
    flex: 1
  },
})